package com.esl.coordinator.util;

import com.esl.coordinator.exception.IPAddressFormatException;
import com.esl.coordinator.exception.MacAddressFormatException;

public final class ESLCommandUtil {
	public static String getMacLowByte(String macAdd)
			throws MacAddressFormatException {
		String[] atoms = macAdd.split("-");
		if (atoms.length != 2) {
			throw new MacAddressFormatException(macAdd);
		} else {
			return atoms[1];
		}
	}

	public static String getMacHighByte(String macAdd)
			throws MacAddressFormatException {
		String[] atoms = macAdd.split("-");
		if (atoms.length != 2) {
			throw new MacAddressFormatException(macAdd);
		} else {
			return atoms[0];
		}
	}

	public static String getIPLowByte(String ipAdd)
			throws IPAddressFormatException {
		String[] atoms = ipAdd.split("\\.");
		if (atoms.length != 4) {
			throw new IPAddressFormatException(ipAdd);
		} else {
			return Hex.toHexString(Integer.valueOf(atoms[3]));
		}
	}

	public static String getIPHighByte(String ipAdd)
			throws IPAddressFormatException {
		String[] atoms = ipAdd.split("\\.");
		if (atoms.length != 4) {
			throw new IPAddressFormatException(ipAdd);
		} else {
			return Hex.toHexString(Integer.valueOf(atoms[2]));
		}
	}

	public static String getHexByteByByteIndex(String hexStr, int index) {
		int adjustedByteIndex = index * 2;
		if (hexStr != null && hexStr.length() % 2 == 0
				&& hexStr.length() > adjustedByteIndex) {
			return hexStr.substring(adjustedByteIndex, adjustedByteIndex + 2);
		} else {
			return "00";
		}
	}
}
